package cn.edu.xmu.orderpayment.order.mq.listener;

import cn.edu.xmu.oomall.core.util.ReturnObject;
import cn.edu.xmu.orderpayment.order.dao.OrderDao;
import cn.edu.xmu.orderpayment.order.microservice.GoodsService;
import cn.edu.xmu.orderpayment.order.microservice.vo.QuantityVo;
import cn.edu.xmu.orderpayment.order.model.bo.Order;
import cn.edu.xmu.orderpayment.order.model.po.OrderItemPo;
import cn.edu.xmu.orderpayment.order.model.po.OrderPo;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static cn.edu.xmu.privilegegateway.annotation.util.Common.cloneVo;

/**
* @Author: Li Yixuan 22920192204232
* @Date: 2021/12/28
*/
@Service
@RocketMQMessageListener(topic = "order-check-topic2",  consumeMode = ConsumeMode.CONCURRENTLY, consumeThreadMax = 10, consumerGroup = "order-check-group2")
public class OrderCheckListener implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {
    private static final Logger logger = LoggerFactory.getLogger(OrderCheckListener.class);

    @Autowired
    private OrderDao orderDao;


    @Autowired
    private GoodsService goodsService;


    @Override
    public void onMessage(String orderSn) {
        // 消费者检查 订单是否已支付，未支付则取消掉
        logger.info("orderListen:"+orderSn+"time:"+ LocalDateTime.now());

        ReturnObject ret=orderDao.getOrderByOrderSn(orderSn);
        if(ret.getData()==null)return;
        OrderPo po= (OrderPo) ret.getData();
        Order order=cloneVo(po,Order.class);
        if(order.getState()== Order.State.NEW_ORDER.getCode()){
            order.setState(Order.State.CANCELED.getCode());
            ReturnObject<List> ret1=orderDao.getOrderItemsByOrderId(order.getId());
            if(ret1.getData()==null)return ;
            List<OrderItemPo> pos=ret1.getData();
            for(OrderItemPo itemPo:pos){
                goodsService.updateOnsaleQuantity(itemPo.getOnsaleId(),new QuantityVo(Math.toIntExact(itemPo.getQuantity())));
                //直接调用必做模块api可能有错
                goodsService.increaseOnSale(itemPo.getShopId(),itemPo.getOnsaleId(),new QuantityVo(Math.toIntExact(itemPo.getQuantity())));
            }
            orderDao.updateOrder(order,order.getCreatorId(),order.getCreatorName());
        }
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        logger.info("prepareStart: consumergroup =" + defaultMQPushConsumer.getConsumerGroup());
    }
}
